package com.example.spring_project.utils;


import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Component
public class TokenUil {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;


    public String generateToken(String userId, String uuid,String code) {
        String token = IdUtils.fastUUID();
        Map<String, Object> claims = new HashMap<>();
        claims.put("LoginUser_Key", token);
        claims.put("userId",userId);
        claims.put("uuid",uuid);
        claims.put("code",code);
        token =  createToken(claims);
        if (!checkToken(token)){
            redisTemplate.opsForValue().set(token,uuid,expireTime, TimeUnit.SECONDS);
        }
        return token;
    }


    private String createToken(Map<String, Object> claims)
    {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    public Boolean checkToken(String token){
        return Boolean.TRUE.equals(redisTemplate.hasKey(token));
    }
}
